from django.contrib.auth import login, authenticate, logout
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from django import http
import re
from django.db import DatabaseError

from leaseList.models import leaseList
from users.models import User
from book_manager.utils.response_code import RETCODE
from django.contrib.auth.mixins import LoginRequiredMixin


# 图书列表
class BookList(LoginRequiredMixin, View):
    def get(self, request):
        # 首先找到cookie 中的数据：
        user_name = request.COOKIES.get('username')
        # print(user_name)
        # 然后从数据库中取到全部信息
        datas = leaseList.objects.filter(name=user_name)
        return render(request, 'book_list.html', {'lists': datas})


# 用户列表展开
class UserInfoView(LoginRequiredMixin, View):
    def get(self, request):
        context = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'grade': request.user.grade,
            'user_college': request.user.user_college,
            'professional': request.user.professional,
            'user_class': request.user.user_class,
            'borrow_number': request.user.number,
        }
        print(request.user.number)
        return render(request, 'user_center_info.html', context)


#  退出
class LoginoutView(View):
    def get(self, request):
        # 退出
        logout(request)
        # 删除cookie,并响应到首页
        response = redirect(reverse('contents:index'))
        response.delete_cookie('username')
        return response


# 登录
class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        # 接收参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')
        # 校验参数
        if not all([username, password]):
            return http.HttpResponseForbidden('缺少必传的参数')
        # if not re.match(r'^[a-zA-Z0-9_-]{2,11}$', username):
        #     return http.HttpResponseForbidden('请输入正确的用户名')
        if not re.match(r'^\d{6}$', password):
            return http.HttpResponseForbidden('密码错误')
        # 认证用户
        user = authenticate(username=username, password=password)
        print(user.username, user.mobile, user.professional)
        if user is None:
            return render(request, 'login.html', {'account_errmsg': '账号或密码错误'})
        if user.is_deleted == True:
            return HttpResponse("<h1>您暂时没有权限登录</h1>")
        else:
            login(request, user)
            if remembered != 'on':
                request.session.set_expiry(0)
            else:
                request.session.set_expiry(None)
            # 登录完成显示首页用户名
            next = request.GET.get('next')
            if next:
                response = redirect(next)
            else:
                response = redirect(reverse('contents:index'))
            print(user.username)
            response.set_cookie('username', user.username, max_age=3600 * 24 * 15)
            return response


class MobileCountView(View):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'Ok', 'count': count})


# 判断用户名是否重复.
class UsernameCountView(View):
    """判断用户名是否重复注册"""

    def get(self, request, username):
        """
        :param username: 用户名
        :return: JSON
        """
        # 实现主体业务逻辑：使用username查询对应的记录的条数(filter返回的是满足条件的结果集)
        count = User.objects.filter(username=username).count()
        # 响应结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


# 注册用户
class RegisterView(View):
    '''用户注册'''

    def get(self, request):
        '''提供用户注册页面'''
        return render(request, 'register.html')

    def post(self, request):
        """实现后端用户注册逻辑"""
        # 接收参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')  # 学号，别问为什么是学号
        grade = request.POST.get('grade')  # 年级
        user_college = request.POST.get('user_college')  # 所属学院
        # user_class = request.POST.get('user_class')  # 班级
        professional = request.POST.get('professional')  # 专业
        # allow = request.POST.get('allow')
        print(user_college)
        print(professional)

        # 校验参数
        # 1.判断参数是否齐全
        if not all([username, password, password2, mobile]):
            return http.HttpResponseForbidden('缺少必传的参数')
        # 2.判断用户名是不是2-10个字符
        # if not re.match(r'^[a-zA-Z0-9_-]{2,10}$', username):
        #     return http.HttpResponseForbidden('请输入用户名注册')
        # 3.判断密码是否是6位
        if not re.match(r'^\d{6}$', password):
            return http.HttpResponseForbidden('请输入一个6位密码')
        # 4.判断两次的密码是不是相同
        if password != password2:
            return http.HttpResponseForbidden('请输入相同的密码')
        # 5.判断用户是否勾选了协议
        # if allow != 'on':
        #     return http.HttpResponseForbidden('请勾选协议')
        # 保存到数据库中
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile,
                                            grade=grade, user_college=user_college,
                                            professional=professional)
        except DatabaseError:
            return render(request, 'register.html', {'register_errmsg': '注册失败'})
        # 实现注册完之后登录
        # login(request, user)
        # 响应结果
        # return http.HttpResponse('注册成功，重定向到首页')
        # return redirect('/')
        response = redirect(reverse('administrator:user_manage'))
        # response.set_cookie('username', user.username, max_age=3600 * 24 * 15)
        return response
